<script setup lang="ts">
import { isEmpty, isEqual, sortBy } from 'lodash-es'
import dayjs from 'dayjs'
import iconShow from '@/assets/img/record/icon-show.png'
import iconCancel from '@/assets/img/record/cancel.png'
import iconConfirm from '@/assets/img/record/confirm.png'
import { orderStatus } from '@/config/orderStatus'
import { computed, ref, watch, nextTick } from 'vue'
import { useGameStore } from '@/stores/game'
import { findHistoryPage, findPlayMenu } from '@/api'
import { DropdownItemInstance, Picker, DatePicker, DropdownMenu, DropdownItem, Field, Popup } from 'vant'

type Props = {
  lotteryCode: string
}

const props = defineProps<Props>()
const emit = defineEmits(['change'])

const gameStore = useGameStore()
const gameList = computed(() => gameStore?.gameList)
const gameOptions = computed(() => {
  const arr = (gameList?.value || []).map((value) => ({ text: value.lotteryName, value: value.lotteryCode }))
  arr.unshift({ text: '全部', value: '' })
  return arr
})

const playTypeCodeOptions = ref([])
const periodsNumberOptions = ref([])

const now = dayjs().utc()
const sixMonthsAgo = now.subtract(6, 'months')
const minDate = new Date(sixMonthsAgo.get('year'), sixMonthsAgo.get('month'), sixMonthsAgo.get('date'))
const maxDate = new Date(now.get('year'), now.get('month'), now.get('date'))

const dateRangeOptions = [
  {
    text: '全部',
    value: undefined,
  },
  {
    text: '昨天',
    value: -1,
  },
  {
    text: '当天',
    value: 0,
  },
  {
    text: '近三天',
    value: 3,
  },
  {
    text: '近七天',
    value: 7,
  },
]

const orderStatusOptions = [{ text: '全部', value: undefined }, ...orderStatus]

const getDateRangeParsed = (value?: number | undefined) => {
  if (value === undefined) {
    return [
      dayjs.utc().subtract(6, 'months').startOf('day').format('YYYY-MM-DD HH:mm:ss'),
      dayjs.utc().endOf('day').format('YYYY-MM-DD HH:mm:ss'),
    ]
  }

  if (value === 0) {
    return [
      dayjs().utc().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
      dayjs.utc().endOf('day').format('YYYY-MM-DD HH:mm:ss'),
    ]
  }

  if (value < 0) {
    return [
      dayjs.utc().subtract(Math.abs(value), 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss'),
      dayjs.utc().subtract(1, 'days').endOf('day').format('YYYY-MM-DD HH:mm:ss'),
    ]
  }

  return [
    dayjs.utc().subtract(value, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss'),
    dayjs.utc().endOf('day').format('YYYY-MM-DD HH:mm:ss'),
  ]
}

const dateRangeResolve = (dateRange: string[]) => {
  const findItem = dateRangeOptions.find((value) => isEqual(getDateRangeParsed(value.value), dateRange))
  if (!isEmpty(findItem)) {
    return findItem.text
  }
  return dateRange.join('~')
}

const cacheFilterForm = ref({
  dateRange: getDateRangeParsed(0),
  periodsNumber: undefined,
  playTypeCode: undefined,
})

const currentFilterForm = ref({
  lotteryCode: props.lotteryCode,
  dateRange: getDateRangeParsed(0),
  lotteryStatus: undefined,
  playTypeCode: undefined,
  periodsNumber: undefined,
})
const currentEditDate = ref([])
const currentEditDateType = ref<'startTime' | 'endTime'>('startTime')

const showDatePicker = ref(false)
const showPeriodsNumberPicker = ref(false)
const dateRangeDropdownItemRef = ref<DropdownItemInstance>()
const lotteryStatusDropdownItemRef = ref<DropdownItemInstance>()
const periodsNumberDropdownItemRef = ref<DropdownItemInstance>()
const playTypeCodeDropdownItemRef = ref<DropdownItemInstance>()

const isSelectMaxDataRange = computed(() => {
  return isEqual(currentFilterForm.value.dateRange, getDateRangeParsed(dateRangeOptions[0].value))
})

const lotteryCodeLabel = computed(() => {
  return isEmpty(currentFilterForm.value.lotteryCode)
    ? '全部'
    : gameOptions.value.find((value) => value.value === currentFilterForm.value.lotteryCode)?.text
})

const dateRangeLabel = computed(() => {
  return isSelectMaxDataRange.value ? '选择时间' : dateRangeResolve(currentFilterForm.value.dateRange)
})

const lotteryStatusLabel = computed(() => {
  return isEmpty(currentFilterForm.value.lotteryStatus)
    ? '派奖状态'
    : orderStatus.find((value) => value.value === currentFilterForm.value.lotteryStatus)?.text
})

const playTypeCodeLabel = computed(() => {
  return isEmpty(currentFilterForm.value.playTypeCode)
    ? '投注玩法'
    : playTypeCodeOptions.value.find((value) => value.value === currentFilterForm.value.playTypeCode)?.text
})

const periodsNumberLabel = computed(() => {
  return isEmpty(currentFilterForm.value.periodsNumber) ? '选择期号' : `第${currentFilterForm.value.periodsNumber}期`
})

const setCurrentEditDate = (e: string, type: typeof currentEditDateType.value) => {
  const date = dayjs(e)
  currentEditDate.value = [date.get('year'), date.get('month') + 1, date.get('dates')]
  currentEditDateType.value = type
  showDatePicker.value = true
}

const onCurrentEditDateConfirm = ({ selectedValues }: { selectedValues: string[] }) => {
  const date = dayjs(selectedValues.join('-')).format('YYYY-MM-DD HH:mm:ss')
  currentEditDateType.value === 'startTime'
    ? (cacheFilterForm.value.dateRange[0] = date)
    : (cacheFilterForm.value.dateRange[1] = date)

  cacheFilterForm.value.dateRange = sortBy(cacheFilterForm.value.dateRange)

  showDatePicker.value = false
}

const onPeriodsNumberConfirm = ({ selectedValues }) => {
  cacheFilterForm.value.periodsNumber = selectedValues[0]
  showPeriodsNumberPicker.value = false
}

const resetCacheFilterForm = () => {
  cacheFilterForm.value = { ...currentFilterForm.value }
  dateRangeDropdownItemRef.value.toggle(false)
  periodsNumberDropdownItemRef.value.toggle(false)
  playTypeCodeDropdownItemRef.value.toggle(false)
}

const confirmCurrentFilterForm = () => {
  currentFilterForm.value = JSON.parse(JSON.stringify({ ...cacheFilterForm.value }))
  dateRangeDropdownItemRef.value.toggle(false)
  periodsNumberDropdownItemRef.value.toggle(false)
  playTypeCodeDropdownItemRef.value.toggle(false)
  emit('change', { ...currentFilterForm.value })
}

const onLotteryStatusOpen = () => {
  nextTick(() => {
    const vanPopupNode = lotteryStatusDropdownItemRef.value.$el.querySelector('.van-popup')
    vanPopupNode.style.opacity = 0
    const nodeRect = document.querySelector('.lottery-status').getBoundingClientRect()
    vanPopupNode.style.left = `${nodeRect.x - 2}px`
    vanPopupNode.style.opacity = 1
  })
}

const fetchPlayMenu = async () => {
  const params = { lotteryCode: currentFilterForm.value.lotteryCode }

  const result = !!params.lotteryCode && (await findPlayMenu(params))

  playTypeCodeOptions.value = [
    { text: '全部', value: undefined },
    ...(result?.data || []).map((v) => ({ text: v.playTypeName, value: v.playTypeCode })),
  ]
}

const fetchHistoryPage = async () => {
  let startTime = dayjs(currentFilterForm.value.dateRange[0])
  let endTime = dayjs(currentFilterForm.value.dateRange[1])

  startTime = startTime.startOf('day').format('YYYY-MM-DD HH:mm:ss')
  endTime = endTime.endOf('day').format('YYYY-MM-DD HH:mm:ss')

  const params = { lotteryCode: currentFilterForm.value.lotteryCode, startTime, endTime }
  const result = !!params.lotteryCode && (await findHistoryPage(params))

  periodsNumberOptions.value = (result?.data?.records || []).map((v) => ({
    text: `第${v.periodsNumber}期`,
    value: v.periodsNumber,
  }))
}

fetchPlayMenu()

watch(
  () => [currentFilterForm.value.dateRange],
  async (value, oldValue) => {
    if (isEqual(value, oldValue)) return
    currentFilterForm.value.periodsNumber = undefined
    await fetchHistoryPage()
  },
  { deep: true, immediate: true },
)

watch(
  () => [currentFilterForm.value.lotteryCode],
  async (value, oldValue) => {
    if (isEqual(value, oldValue)) return
    currentFilterForm.value.dateRange = getDateRangeParsed(0)
    currentFilterForm.value.lotteryStatus = undefined
    currentFilterForm.value.playTypeCode = undefined
    currentFilterForm.value.periodsNumber = undefined
    resetCacheFilterForm()
    await fetchHistoryPage()
    await fetchPlayMenu()
    emit('change', { ...currentFilterForm.value })
  },
)

watch(
  () => [currentFilterForm.value.lotteryStatus],
  (value, oldValue) => {
    if (isEqual(value, oldValue)) return
    cacheFilterForm.value = { ...currentFilterForm.value }
    emit('change', { ...currentFilterForm.value })
  },
  { deep: true, immediate: true },
)
</script>

<template>
  <div class="filter-box">
    <div class="filter-btn-group">
      <DropdownMenu swipe-threshold="4">
        <Popup v-model:show="showDatePicker" position="bottom">
          <DatePicker
            v-model="currentEditDate"
            title="选择日期"
            :min-date="minDate"
            :max-date="maxDate"
            @cancel="showDatePicker = false"
            @confirm="onCurrentEditDateConfirm"
          />
        </Popup>
        <Popup v-model:show="showPeriodsNumberPicker" round position="bottom" class="period-pick">
          <Picker
            :columns="periodsNumberOptions"
            @cancel="showPeriodsNumberPicker = false"
            @confirm="onPeriodsNumberConfirm"
          />
        </Popup>
        <DropdownItem
          class="narrow"
          v-model="currentFilterForm.lotteryCode"
          :options="gameOptions"
          @change="(v) => (currentFilterForm.lotteryCode = v)"
          :title="lotteryCodeLabel"
        />
        <DropdownItem ref="dateRangeDropdownItemRef" :title="dateRangeLabel">
          <div class="date-range">
            <div class="dates">
              <span
                v-for="item of dateRangeOptions"
                :key="item.text"
                :class="{
                  active: isEqual(cacheFilterForm.dateRange, getDateRangeParsed(item.value)),
                }"
                @click="cacheFilterForm.dateRange = getDateRangeParsed(item.value)"
              >
                {{ item.text }}
              </span>
            </div>
            <div
              class="data-input"
              v-if="!isEqual(cacheFilterForm.dateRange, getDateRangeParsed(dateRangeOptions[0].value))"
            >
              <span @click="setCurrentEditDate(cacheFilterForm.dateRange[0], 'startTime')">
                {{ dayjs(cacheFilterForm.dateRange[0]).format('YYYY-MM-DD') }}
                <img :src="iconShow" alt="" />
              </span>
              至
              <span @click="setCurrentEditDate(cacheFilterForm.dateRange[1], 'endTime')">
                {{ dayjs(cacheFilterForm.dateRange[1]).format('YYYY-MM-DD') }}
                <img :src="iconShow" alt="" />
              </span>
            </div>
            <div class="bottom-confirm">
              <img :src="iconCancel" @click="resetCacheFilterForm" alt="cancel" />
              <img :src="iconConfirm" @click="confirmCurrentFilterForm" alt="confirm" />
            </div>
          </div>
        </DropdownItem>
        <DropdownItem
          title-class="lottery-status"
          class="narrow"
          ref="lotteryStatusDropdownItemRef"
          @open="onLotteryStatusOpen"
          v-model="currentFilterForm.lotteryStatus"
          :options="orderStatusOptions"
          :title="lotteryStatusLabel"
        />
        <DropdownItem ref="periodsNumberDropdownItemRef" :title="periodsNumberLabel">
          <div class="periods-number">
            <Field
              v-model="cacheFilterForm.periodsNumber"
              is-link
              readonly
              label=""
              placeholder="请选择期号"
              @click="showPeriodsNumberPicker = true"
            />
            <div class="bottom-confirm">
              <img :src="iconCancel" @click="resetCacheFilterForm" alt="cancel" />
              <img :src="iconConfirm" @click="confirmCurrentFilterForm" alt="confirm" />
            </div>
          </div>
        </DropdownItem>
        <DropdownItem
          ref="playTypeCodeDropdownItemRef"
          class="play-type-code"
          v-model="cacheFilterForm.playTypeCode"
          :options="playTypeCodeOptions"
          :title="playTypeCodeLabel"
          @change="
            () => {
              playTypeCodeDropdownItemRef.toggle(true)
            }
          "
        >
          <div class="bottom-confirm">
            <img :src="iconCancel" @click="resetCacheFilterForm" alt="cancel" />
            <img :src="iconConfirm" @click="confirmCurrentFilterForm" alt="confirm" />
          </div>
        </DropdownItem>
      </DropdownMenu>
    </div>
  </div>
</template>

<style scoped lang="less">
.filter-box {
  display: flex;
  width: 100%;
  align-items: center;
  background-color: #171a26;
  padding: 6px 0;

  :deep(.van-popup) {
    background: rgba(23, 26, 38, 1);
  }

  .bottom-confirm {
    display: flex;
    width: 100%;
    align-items: center;
    gap: 34px;
    justify-items: center;
    justify-content: center;

    img {
      width: 120px;
      height: 32px;
    }
  }

  .filter-btn-group {
    width: 100%;
    color: rgba(181, 188, 255, 1);
    height: 30px;

    :deep(.van-dropdown-menu) {
      height: 100%;

      .van-dropdown-menu__bar {
        height: 100%;
        padding: 0 5px;
        background: transparent;
        box-shadow: unset;
        gap: 5px;

        .van-dropdown-menu__item {
          height: calc(100% - 2px);
          border-radius: 3px;
          background-color: #272c5d;
          padding: 0;
          border: 0.5px solid rgba(71, 79, 157, 1);
          background: linear-gradient(0deg, #272c5d, #272c5d);
        }

        .van-dropdown-menu__title {
          padding: 0;
          width: 80px;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          justify-items: center;

          &:after {
            position: relative;
            top: auto;
            right: auto;
            margin-top: 0;
            border: 0;
            opacity: 1;
            background-image: url('@/assets/img/record/icon-show.png');
            background-size: 100% 100%;
            width: 9px;
            height: 5px;
            transform: rotate(0deg);
            margin-left: 6px;
          }

          .van-ellipsis {
            max-width: 1rem;
            color: #b5bcff;
          }

          &.van-dropdown-menu__title--active {
            background: rgba(101, 90, 227, 1);
            border-radius: 3px;

            .van-ellipsis {
              color: white;
            }

            &:after {
              background-image: url('@/assets/img/record/icon-up.png');
            }
          }
        }

        .van-ellipsis {
          font-size: 12px;
          color: rgba(181, 188, 255, 1);
        }
      }
    }
  }

  .date-range {
    display: flex;
    width: 100%;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    justify-items: center;
    gap: 16px;
    padding: 10px 0;

    .dates {
      display: flex;
      width: 100%;
      align-items: center;
      gap: 7px;
      justify-items: center;
      justify-content: center;

      span {
        width: 56px;
        height: 24px;
        line-height: 24px;
        text-align: center;
        font-size: 11px;
        border-radius: 3px;
        border: 0.5px solid rgba(117, 125, 205, 1);
        background: linear-gradient(0deg, #272c5d, #272c5d);
        color: rgba(181, 188, 255, 1);

        &.active {
          color: white;
          background: linear-gradient(0deg, #655ae3, #655ae3);
          border: 0.5px solid rgba(117, 125, 205, 1);
        }
      }
    }

    .data-input {
      display: flex;
      width: 100%;
      align-items: center;
      gap: 10px;
      justify-items: center;
      justify-content: center;
      color: #fff;

      span {
        width: 133px;
        height: 23px;
        border: 0.5px solid rgba(91, 97, 156, 1);
        border-radius: 100px;
        color: rgba(120, 129, 204, 1);
        font-size: 11px;
        position: relative;
        display: inline-flex;
        align-items: center;
        justify-items: center;
        justify-content: center;

        img {
          position: absolute;
          right: 15px;
          height: 6px;
        }
      }
    }
  }

  .narrow {
    :deep(.van-popup) {
      width: 84px;
      left: 2.5px;
      box-shadow: 0 0 4px 0 #24050540;
      border-radius: 3px;

      .van-cell {
        padding: 0;
        width: 100%;
        height: 38px;
        display: flex;
        align-items: center;
        background: #272c5d;

        &:after {
          display: none;
        }

        &.van-dropdown-item__option--active {
          background-color: #655ae3;

          .van-cell__title {
            color: white;
          }
        }

        .van-cell__title {
          width: 100%;
          display: flex;
          align-items: center;
          justify-items: center;
          justify-content: center;
          font-size: 12px;
          color: #b5bcff;
        }

        .van-cell__value {
          display: none;
        }
      }
    }
  }

  .play-type-code {
    :deep(.van-popup) {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      justify-items: flex-start;
      justify-content: flex-start;
      padding: 14px 20px;

      .van-cell__value {
        display: none;
      }

      .van-cell {
        padding: 0;
        width: 76px;
        height: 24px;
        display: flex;
        align-items: center;

        &:after {
          display: none;
        }

        &.van-dropdown-item__option {
          background-color: transparent;
        }

        &.van-dropdown-item__option--active {
          // background-color: transparent;
          // border-radius: 3px;

          .van-cell__title {
            color: white;
            border: 0.5px solid rgba(117, 125, 205, 1);
            background: linear-gradient(0deg, #655ae3, #655ae3);
          }
        }

        .van-cell__title {
          width: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 12px;
          color: rgba(181, 188, 255, 1);
          border: 0.5px solid rgba(117, 125, 205, 1);
          height: calc(100% - 2px);
          border-radius: 3px;
          background: linear-gradient(0deg, #272c5d, #272c5d);
        }

        .van-cell__value {
          display: none;
        }
      }
    }
  }

  .periods-number {
    display: flex;
    flex-direction: column;
    gap: 38px;
    padding: 13px 0;
    justify-content: center;
    justify-items: center;
    align-items: center;

    :deep(.van-cell) {
      width: 274px;
      border: 1px solid rgba(65, 70, 112, 1);
      border-radius: 100px;
      padding: 0 14px;
      height: 30px;
      background: transparent;

      .van-cell__right-icon {
        color: rgba(120, 129, 204, 0.8);
      }

      &::after {
        display: none;
      }

      .van-field__body,
      .van-badge__wrapper {
        height: 100%;
      }

      .van-badge__wrapper {
        line-height: 1.7;
        transform: rotate(90deg);
      }

      .van-field__control {
        font-size: 12px;
        color: rgba(120, 129, 204, 0.8);

        &::placeholder {
          color: rgba(120, 129, 204, 0.8);
        }
      }
    }
  }
}
</style>
